<template>
    <MyDialog title="Order Hard Time Replacement" :mode="props.mode" :submit="submitFn">
      <div class="q-gutter-md q-pa-md">
      <q-select
        v-model="state.data.serial_no"
        label="Serial No"
        :options="options"
        borderless
        class="input-css"
      />
      <q-input
        v-model="state.data.component"
        type="text"
        label="Component"
        borderless
        class="input-css"
      />

      <!-- <q-input v-model="state.data.period" type="text" label="Period(Months)" filled /> -->
    </div>
    </MyDialog>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import {
  createOrderHtreplace,
  getOrderParts,
} from 'src/services/repairService';
import { patchStockItemHtreplace } from 'src/services/stockCodeService';
import { onMounted, reactive, ref } from 'vue';
import MyDialog from '../container/MyDialog.vue';

const emit = defineEmits(['submit', 'close']);

const $q = useQuasar();
const props = defineProps<{
  mode: 'edit' | 'create';
  orderId?: number;
}>();

const state = reactive<{
  data: {
    order_id: number
    serial_no: string
    component: string
  };
}>({
  data: {
    order_id: 0,
    serial_no: '',
    component: '',
  },
});

const snOption = ref<string[]>([]);
const options = ref(snOption);

const orderPartMap = new Map()

async function initData() {
  if (props.orderId) {
    const res = await getOrderParts(props.orderId);
    if (res.data) {
      for (let d of res.data) {
        if(d.serial_no!=''){
          snOption.value.push(d.serial_no);
          orderPartMap.set(d.serial_no, d.id)
        }
      }      
    }
  }
}

async function create() {
  if (props.orderId) {
    const orderPartId = orderPartMap.get(state.data.serial_no)
    
    const createRes = await createOrderHtreplace(
      orderPartId,
    props.orderId,
    state.data.component
    );

    if (createRes) {
      $q.notify({
        color: 'positive',
        message: 'Created',
        icon: 'check',
      });
      emit('submit');
      emit('close');
    }
  }
}

async function edit() {
  if (props.orderId) {
    const res = await patchStockItemHtreplace(props.orderId, 1);
    if (res) {
      emit('submit');
      emit('close');
    }
  }
  return;
}

function submitFn() {
  if (props.mode == 'create') {
    create();
  } else {
    edit();
  }
}

function closeFn() {
  emit('close');
}

onMounted(() => {
  initData();
});
</script>

<style scoped>
.cap {
  text-transform: capitalize;
}
</style>
